﻿namespace Library.Storage
{
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.IO.IsolatedStorage;
    using System.IO;

    public class StorageProvider
    {
        public StorageProvider()
        {
            this.DefaultSerializer = new JsonSerializer();
        }

        public ISerializer DefaultSerializer { get; set; }

        public void WriteToFile(string key, object value)
        {
            this.WriteToFile(key, value, this.DefaultSerializer);
        }

        public void WriteToFile<T>(string key, T value, ISerializer serialzier)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = store.OpenFile(key, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    serialzier.Serialize<T>(stream, value);
                }
            }
        }

        public T ReadFromFile<T>(string key)
        {
            return this.ReadFromFile<T>(key, this.DefaultSerializer);
        }

        public T ReadFromFile<T>(string key, ISerializer serializer)
        {
            T result = default(T);
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(key))
                {
                    using (var stream = store.OpenFile(key, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        result = serializer.Deserialize<T>(stream);
                    }
                }
            }

            return result;
        }
    }
}
